package com.amazon.shop.filter.globalwebfilter;

import com.alibaba.fastjson.JSONObject;
import com.amazon.shop.bean.entity.User;
import com.amazon.shop.bean.vo.Ret;
import lombok.extern.log4j.Log4j2;
import org.apache.logging.log4j.ThreadContext;
import org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 
 * 创建时间：2019年9月19日 上午11:13:47
 * 
 * 项目名称：rebatencenter
 * 
 * @author wanglong
 * 
 * @version 1.0
 * 
 * @since JDK 1.8.0_171
 * 
 *        文件名称：WebFilterParam.java
 * 
 *        类说明：过滤器，对加密接口就行解密
 *
 *        Modification History: Date Author Version Description
 *        ---------------------------------------------------------*
 */
@Log4j2
public class WebFilterParam extends OncePerRequestFilter {

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		String uri = request.getServletPath();
		if(uri.contains("batchExport")){
			filterChain.doFilter(request, response);
			return;
		}
		long timestamp = System.currentTimeMillis();
		ResponseWrapper wrapper = new ResponseWrapper(response);
		// 生成唯一请求id
		String taskId = WebUtil.resolveReqId();
		String ipaddress = WebUtil.getRequestIp();

		String url = request.getRequestURL().toString();
		ThreadContext.put("taskId", taskId);
		Map<String, String[]> parameterMap = new HashMap<>(request.getParameterMap());
		parameterMap.put("taskId", new String[]{taskId});
		parameterMap.put("ip", new String[]{ipaddress});
		parameterMap.put("timestamp", new String[]{timestamp+""});
		User user = (User) request.getSession().getAttribute("user");
		//添加操作人信息
		if (user!=null) {
			parameterMap.put("operatorUserid", new String[]{user.getId()+""});
			parameterMap.put("operator", new String[]{user.getNickname()+""});
			parameterMap.put("oismanager", new String[]{user.getIsmanager()+""});
		}
		ParameterRequestWrapper wrapRequest = new ParameterRequestWrapper(request,parameterMap);
		request = wrapRequest;
		//请求日志
		StringBuilder logStr = new StringBuilder();
		logStr.append(timestamp);
		logStr.append("\t【REQUEST】");
		logStr.append("\t"+taskId);
		logStr.append("\t" + ipaddress);
		logStr.append("\t" + url);
		logStr.append("\t"+JSONObject.toJSONString(parameterMap));
		log.info(logStr);
		//执行mvc
		super.doFilter(request, wrapper, filterChain);
		//处理返回结果
		byte[] result = wrapper.getResponseData();
		byte[] retstr = new byte[0];
		String str = "";
		if(result!=null&&result.length>0){
			str = new String(result,response.getCharacterEncoding());
			Ret ret = JSONObject.parseObject(str, Ret.class);
			ret.setTaskId(taskId);
			retstr = JSONObject.toJSONBytes(ret);
		}
		ServletOutputStream outputStream = response.getOutputStream();
		outputStream.write(retstr);
		outputStream.flush();
		outputStream.close();
		//返回日志
		logStr.setLength(0);
		long endtime = System.currentTimeMillis();
		logStr.append(endtime);
		logStr.append("\t【RESPONSE】");
		logStr.append("\t"+taskId);
		logStr.append("\t" + ipaddress);
		logStr.append("\t" + url);
		logStr.append("\t"+str);
		logStr.append("\t"+(endtime-timestamp));
		log.info(logStr);
		ThreadContext.remove("taskId");
	}
}
